package client

import (
	"fmt"

	. "chess_platform/internal/common"
	"github.com/astaxie/beego/orm"
)

//支付相关

//列出商城商品
func ListProduct(multiOrm ...orm.Ormer) ([]Store, error) {
	var store []Store
	err := GetCache(RedisCache, KeyStoreList, &store)
	if err != nil {
		sql := fmt.Sprintf(`SELECT * FROM %v ORDER BY num
		`, TableStore)
		o := NewOrm(multiOrm, DBChessSysData)
		_, err := o.Raw(sql).QueryRows(&store)
		if CheckError(err) {
			return nil, err
		}
		SetCache(RedisCache, KeyStoreList, store, CacheExpire)
	}
	return store, nil
}

//查找单个商品的详情
func ProductById(id int64, multiOrm ...orm.Ormer) (s Store, err error) {
	storeList, err := ListProduct(multiOrm...)
	if err != nil {
		return s, err
	}
	for _, v := range storeList {
		if id == v.Id {
			return v, nil
		}
	}
	return s, nil
}

//根据苹果的产品ID查找商品
func ProductByAppleProductId(productId int64, multiOrm ...orm.Ormer) (s Store, err error) {
	storeList, err := ListProduct(multiOrm...)
	if err != nil {
		return s, err
	}
	for _, v := range storeList {
		if productId == v.ProductId {
			return v, nil
		}
	}
	return s, nil

}

func ListDiamondCoin(multiOrm ...orm.Ormer) ([]*DiamondCoin, error) {
	var dc []*DiamondCoin
	err := GetCache(RedisCache, KeyDiamondCoinList, &dc)
	if err != nil {
		sql := fmt.Sprintf(`SELECT * FROM %v ORDER BY diamond
		`, TableDiamondCoin)
		o := NewOrm(multiOrm, DBChessSysData)
		_, err := o.Raw(sql).QueryRows(&dc)
		if CheckError(err) {
			return nil, err
		}
		SetCache(RedisCache, KeyDiamondCoinList, dc, CacheExpire)
	}
	return dc, nil
}
func DiamondCoinById(id int64, multiOrm ...orm.Ormer) (*DiamondCoin, error) {
	dcList, err := ListDiamondCoin(multiOrm...)
	if err != nil {
		return nil, err
	}
	for _, v := range dcList {
		if id == v.Id {
			return v, nil
		}
	}
	return nil, nil
}

//生成订单预支付
func PreOrder(data map[string]interface{}, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChess)
	values, sql := InsertSql(TableAppOrder, data)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.LastInsertId()
}

//查询订单
func OrderById(id interface{}, multiOrm ...orm.Ormer) (*AppOrder, error) {
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
		WHERE
			id = %v
	`, TableAppOrder, id)
	o := NewOrm(multiOrm, DBChess)
	var order AppOrder
	err := o.Raw(sql).QueryRow(&order)
	if CheckNoExist(err) {
		return nil, nil
	}
	return &order, err
}
func UpdateOrder(order map[string]interface{}, id interface{}, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChess)
	condition := fmt.Sprintf(`id = %v`, id)
	values, sql := UpdateSql(TableAppOrder, order, condition)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}
